package com.kd.service.customer;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kd.common.PageResult;
import com.kd.dao.CustomerMapper;
import com.kd.entity.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * 客户服务实现类，继承自 MyBatis-Plus 的 ServiceImpl
 * 1.通过Cid找客户
 * 2.通过手机号找cid
 * 3.查看所有客户列表
 * 4.通过姓名模糊查询客户列表   搜索功能
 * 5.插入客户
 * 6.修改属性
 * 7.获取客户数量
 * 8.
 *
 */

@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements CustomerService {

    @Autowired
    private CustomerMapper customerMapper;
    private final Integer INSERT_SUCESS=1;

    // ===== 查询类方法 =====

    /**
     * 1.通过id找客户
     */
    @Override
// 根据手机号查询（非主键字段）
    public Customer findCustomerByPhone(String phone) {
        QueryWrapper<Customer> wrapper = new QueryWrapper<>();
        wrapper.eq("phone",  phone);
        return customerMapper.selectOne(wrapper);
    }
    @Override
    public Customer findCustomerById(Integer cid) {
        QueryWrapper<Customer> wrapper = new QueryWrapper<>();
        wrapper.eq("cid",  cid);
        return customerMapper.selectOne(wrapper);
    }
    @Override
    public Customer findCustomerById(String cid) {
        QueryWrapper<Customer> wrapper = new QueryWrapper<>();
        wrapper.eq("cid",  cid);
        return customerMapper.selectOne(wrapper);
    }
    /**
     * 2.通过手机号找id
     */
    @Override
    public Integer getCidByphone(String phone) {
        if (StringUtils.isBlank(phone)) return null;
        QueryWrapper<Customer> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);
        Customer customer = customerMapper.selectOne(wrapper);
        return customer != null ? customer.getCid() : null;
    }
    @Override
    public Integer getCidByemail(String email) {
        if (StringUtils.isBlank(email)) return null;
        QueryWrapper<Customer> wrapper = new QueryWrapper<>();
        wrapper.eq("email", email);
        Customer customer = customerMapper.selectOne(wrapper);
        return customer != null ? customer.getCid() : null;
    }

    /**
     * 3.查看所有客户列表
     */
    @Override
    public List<Customer> findCustomerList() {
        return customerMapper.selectList(null);
    }





    /**
     * 4.通过姓名模糊查询客户列表   搜索功能
     */
    @Override
    public List<Customer> findCustomerListByName(String name) {
        QueryWrapper<Customer> wrapper = new QueryWrapper<>();
        wrapper.like("name", name); // 模糊匹配姓名
        return customerMapper.selectList(wrapper);
    }


    ///////////////////////////----------------------------

    /**
     * 基于游标的分页查询 - 所有客户
     */
    @Override
    public PageResult<Customer,Integer> findCustomerListByCursor(Integer cursor, Integer limit) {
        if (limit == null || limit <= 0) {
            limit = 10; // 默认10条
        }

        QueryWrapper<Customer> wrapper = new QueryWrapper<>();

        // 如果有游标，添加条件：cid < cursor
        if (cursor != null && cursor > 0) {
            wrapper.lt("cid", cursor);
        }

        // 按cid倒序排列，确保分页连续性
        wrapper.orderByDesc("cid");

        // 查询 limit + 1 条，用于判断是否有下一页
        List<Customer> customers = customerMapper.selectList(
                wrapper.last("LIMIT " + (limit + 1))
        );

        boolean hasNext = customers.size() > limit;
        List<Customer> resultData = hasNext ?
                customers.subList(0, limit) : customers;

        // 获取下一页的游标（最后一条记录的cid）
        Integer nextCursor = null;
        if (hasNext && !resultData.isEmpty()) {
            nextCursor = resultData.get(resultData.size() - 1).getCid();
        }

        return PageResult.of(resultData, nextCursor, hasNext, limit);
    }

    /**
     * 基于游标的分页查询 - 按姓名模糊查询
     */
    @Override
    public PageResult<Customer,Integer> findCustomerListWithFilters(
            Integer cursor,
            Integer limit,
            Integer cid,
            String name,
            String phone,
            String company,
            Boolean hasLicense
    ) {
        if (limit == null || limit <= 0) {
            limit = 10;
        }

        QueryWrapper<Customer> wrapper = new QueryWrapper<>();

        // 添加过滤条件
        if (cid != null) wrapper.like("cid",  cid);

        if (StringUtils.isNotBlank(name)) {
            wrapper.like("name", name);
        }
        if (StringUtils.isNotBlank(phone)) {
            wrapper.like("phone", phone);
        }
        if (StringUtils.isNotBlank(company)) {
            wrapper.like("company", company);
        }
        if (hasLicense != null) {
            if (hasLicense) {
                wrapper.isNotNull("license_image").ne("license_image", "");
            } else {
                wrapper.isNull("license_image").or().eq("license_image", "");
            }
        }

        // 游标条件（基于cid的分页）
        if (cursor != null && cursor > 0) {
            wrapper.lt("cid", cursor);
        }

        // 按cid倒序排列，确保分页连续性
        wrapper.orderByDesc("cid");

        // 查询 limit + 1 条，用于判断是否有下一页
        List<Customer> customers = customerMapper.selectList(
                wrapper.last("LIMIT " + (limit + 1))
        );

        boolean hasNext = customers.size() > limit;
        List<Customer> resultData = hasNext ?
                customers.subList(0, limit) : customers;

        // 获取下一页的游标（最后一条记录的cid）
        Integer nextCursor = null;
        if (hasNext && !resultData.isEmpty()) {
            nextCursor = resultData.get(resultData.size() - 1).getCid();
        }

        return PageResult.of(resultData, nextCursor, hasNext, limit);
    }

//    @Override
//    public PageResult<Customer, String> findCustomerListWithFiltersandStats(
//            String cursor, Integer limit, Integer cid, String name,
//            String phone, String company, Boolean hasLicense,
//            Integer active_count, BigDecimal cce, Integer cpq,
//            String sortField, Boolean sortDesc) {
//
//        // 1. 参数校验与默认值
//        if (limit == null || limit <= 0) limit = 10;
//        if (sortField == null) sortField = "cid";
//        if (sortDesc == null) sortDesc = false; // 默认升序
//
//        QueryWrapper<Customer> wrapper = new QueryWrapper<>();
//
//        // 2. 基础筛选条件
//        if (cid != null) wrapper.eq("cid",  cid);
//        if (StringUtils.isNotBlank(name))  wrapper.like("name",  name);
//        if (StringUtils.isNotBlank(phone))  wrapper.like("phone",  phone);
//        if (StringUtils.isNotBlank(company))  wrapper.like("company",  company);
//        if (hasLicense != null) {
//            wrapper.apply(hasLicense  ?
//                    "license_image IS NOT NULL AND license_image != ''" :
//                    "license_image IS NULL OR license_image = ''");
//        }
//
//        // 3. 统计字段筛选
//        if (active_count != null) wrapper.eq("active_count",  active_count);
//        if (cce != null) wrapper.eq("cce",  cce);
//        if (cpq != null) wrapper.eq("cpq",  cpq);
//
//        // 4. 复合排序（关键修正）
//        boolean isAsc = !sortDesc;
//        wrapper.orderBy(true,  isAsc, sortField)
//                .orderBy(true, isAsc, "cid"); // 次要排序方向与主排序一致
//
//        // 5. 游标分页处理（关键修正）
//        if (cursor != null) {
//            String[] parts = cursor.split("::");
//            if (parts.length  == 2) {
//                String operator = isAsc ? ">" : "<"; // 根据排序方向确定操作符
//                wrapper.apply("("  + sortField + " " + operator + " " + parts[0] + ")" +
//                        " OR (" + sortField + " = " + parts[0] +
//                        " AND cid " + operator + " " + parts[1] + ")");
//            }
//        }
//
//        // 6. 执行查询
//        List<Customer> customers = customerMapper.selectList(
//                wrapper.last("LIMIT  " + (limit + 1))
//        );
//
//        // 7. 处理分页结果
//        boolean hasNext = customers.size()  > limit;
//        List<Customer> resultData = hasNext ?
//                customers.subList(0,  limit) : customers;
//
//        // 8. 生成复合游标
//        String nextCursor = null;
//        if (hasNext && !resultData.isEmpty())  {
//            Customer last = resultData.get(resultData.size()  - 1);
//            nextCursor = getSortFieldValue(last, sortField) + "::" + last.getCid();
//        }
//
//        return PageResult.of(resultData,  nextCursor, hasNext, limit);
//    }
//
//    private String getSortFieldValue(Customer customer, String sortField) {
//        switch (sortField) {
//            case "active_count": return customer.getActive_count().toString();
//            case "cce": return customer.getCce().toString();
//            case "cpq": return customer.getCpq().toString();
//            default: return customer.getCid().toString();
//        }
//    }


    // ===== 插入类方法 =====

    /**
     * 5.插入新客户（密码加密处理）
     */
    @Override
    public boolean insert(Customer customer) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        customer.setPassword(passwordEncoder.encode(customer.getPassword()));
        return customerMapper.insert(customer)==INSERT_SUCESS;
    }




    // ===== 修改类方法 =====
    /**
     * 6.修改对应属性
     */
    @Override
    public boolean updateCustomer(Customer customer) {
        return customerMapper.updateById(customer)>0;
    }

    /**
     * 7.获取客户统计
     */
    public PageResult<CustomerMapper.CustomerStats, Long> getCustomerStats(
            Long cursor,
            Integer limit,
            boolean isNextPage) {
        // 多查1条用于判断是否有更多数据
        List<CustomerMapper.CustomerStats> statsList = customerMapper.selectCustomerStats(
                cursor,
                limit + 1,
                isNextPage
        );
        // 判断是否还有数据
        boolean hasMore = statsList.size()  > limit;
        if (hasMore) {
            statsList = statsList.subList(0,  limit);
        }
        // 计算下一个游标值
        Long nextCursor = statsList.isEmpty()  ? null :
                statsList.get(statsList.size()  - 1).getCursorValue();
        return PageResult.of(statsList,  nextCursor, hasMore, limit);
    }

}
